package com.scalar.chiptrack.operations.dataentry.lotTransfer.actioncommands;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.dataentry.lotTransfer.forms.TransferMaterialForm;
import com.scalar.chiptrack.operations.dataentry.dao.DataEntryDAO;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.sales.SubTotal;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;

public class TransferMaterialSaveLotDetailsCommand  extends ActionCommand
{
    private static final String ACTION_NAME = "/transferMaterial.do";


    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response ) throws Exception
    {
        TransferMaterialForm transferMaterialForm = ( TransferMaterialForm ) form;

        HashMap<String, String> errors  = new HashMap<String, String>();
        HashMap<String, String> info    = new HashMap<String,String>();

        ArrayList waferInfoList      = new ArrayList();
        String action                = request.getParameter ( "action" );

        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );

        HttpSession mSession              = request.getSession();
        User user                         = ( User ) mSession.getAttribute ( SessionKeys.USER_KEY );

        if ( user == null )
        {
            mSession.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.TRANSFER_MATERIAL , User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

        LotDetails lotsDetails = null;
        LotDetails sortBinlotDetails = null;

        if ( "save".equalsIgnoreCase( action ) )
        {
            LinkedHashMap hash = new LinkedHashMap();
            ArrayList arrList  = new ArrayList();
            String locationType = transferMaterialForm.getBaseprocessType();
           //for Confirm Screen
            for (int i = 0; i < transferMaterialForm.getWipLotsList().size(); i++)
            {
                lotsDetails = (LotDetails) transferMaterialForm.getWipLotsList().get(i);

                if ( lotsDetails.isChecked() )
                {
                    if ("-2".equalsIgnoreCase( lotsDetails.getTransferFrom() ))
                    {
                         lotsDetails.setTransferFrom( lotsDetails.getTransferFrom1() );
                    }
                    if ("-2".equalsIgnoreCase( lotsDetails.getTransferTo() ))
                    {
                         lotsDetails.setTransferTo( lotsDetails.getTransferTo1() );
                    }
                    if ( lotsDetails.getCheckedWaferIdsAsString() == null || lotsDetails.getCheckedWaferIdsAsString().equals("") )
                    {
                        lotsDetails.setCheckedWaferIdsAsString( lotsDetails.getWaferIds() );
                        lotsDetails.setCheckedBinQtyAsString( lotsDetails.getBinQtyAsString() );
                    }
                    if ( locationType.equalsIgnoreCase( LOCATION_TYPE_FAB ) || locationType.equalsIgnoreCase( LOCATION_TYPE_WAFER_STORE )
                        || locationType.equalsIgnoreCase( LOCATION_TYPE_SORT ) || "Back Grind".equalsIgnoreCase(transferMaterialForm.getProcessType() )
                        || locationType.equalsIgnoreCase( LOCATION_TYPE_BUMPING )  )
                    {
                        lotsDetails.setShipDieQty( lotsDetails.getShipQty() ); //TO SHOW iN THE CONFIRM PAGE
                    }

                    if ( locationType.equalsIgnoreCase( LOCATION_TYPE_DIE_BANK ) )
                    {
                        // TO UPDATE THE BIN QTY'S
                        sortBinlotDetails = new LotDetails();
                        sortBinlotDetails.setLotId( lotsDetails.getLotId() );
                        sortBinlotDetails.setCheckedWaferIdsAsString( lotsDetails.getCheckedWaferIdsAsString() );
                        sortBinlotDetails.setCheckedBinQtyAsString( lotsDetails.getBinQtyAsString() );
                        sortBinlotDetails.setTransferTo( lotsDetails.getTransferTo() );
                        waferInfoList.add( sortBinlotDetails );

                        lotsDetails.setShipDieQty( lotsDetails.getDieQtyIn() );
                    }   

                    String partNumber = lotsDetails.getPartNumber();
                    if ( !( hash.containsKey ( partNumber ) ) )
                    {
                        hash.put ( partNumber, new ArrayList() );
                    }
                    arrList = (ArrayList) hash.get ( partNumber );

                    arrList.add ( lotsDetails );
                }
            }

            Iterator iterator = hash.keySet().iterator();
            LinkedHashMap hashMap = new LinkedHashMap ();

            while ( iterator.hasNext () )
            {
                String str = ( String ) iterator.next ();
                ArrayList newarrList = ( ArrayList )hash.get ( str );
                SubTotal subTotal = new SubTotal();
                int subTotalQty = 0;

                for ( int j = 0; j < newarrList.size (); j++ )
                {
                    subTotalQty = subTotalQty + Integer.parseInt ( ( (LotDetails)newarrList.get( j ) ).getShipDieQty() );
                }
                subTotal.setSubTotalQty( Integer.toString ( subTotalQty )  );

                hashMap.put ( newarrList, subTotal );
            }

            request.setAttribute("subTotalMap", hashMap );

            transferMaterialForm.setWaferInfoList(  waferInfoList );

            request.setAttribute("action", action);

            saveToken( request );
            return mapping.findForward( "transferMaterialConfirm" );
        }
        else if ("addNewDepartment".equalsIgnoreCase( action ) )
        {
            return mapping.findForward("addNewDepartment");
        }
        else if ("saveDepartment".equalsIgnoreCase(action) )
        {
            if ( DataEntryDAO.isDepartmentExists(null,transferMaterialForm.getDepartmentName()) )
            {
                 errors.put( transferMaterialForm.getDepartmentName() + "  Already exists in the database", null );
                 transferMaterialForm.reset( mapping,request );

                 return mapping.findForward( "saveDepartment" );
            }
            else
            {
                try
                {
                    DataEntryDAO.saveDepartments(null, transferMaterialForm.getDepartmentName(), transferMaterialForm.getFullAccountNo(), transferMaterialForm.isProdCategory() );
                    request.setAttribute("departmentList", DataEntryDAO.loadDepartmentList(null) );
                    request.setAttribute( "refreshListData", "true");
                    transferMaterialForm.reset( mapping,request );
                    info.put( "Department Name Saved Successfully",null );
                }catch (Exception e)
                {
                   errors.put( "Could not save Department Name information ", null ); 
                }
            }

            return mapping.findForward("saveDepartment");
        }
        else
        {
            if ( isTokenValid( request ))
            {
                try
                {
                    DataEntryDAO.saveTransferedLotDetails( null, transferMaterialForm.getWipLotsList(), user.getUserName(), transferMaterialForm.getBaseprocessType() );

                    if ( transferMaterialForm.getWaferInfoList() != null && transferMaterialForm.getWaferInfoList().size() > 0 )
                    {
                        DataEntryDAO.updateDieBankBinInfo( null, transferMaterialForm.getWaferInfoList() );
                    }
                    resetToken( request );
                    info.put ( "Material Transfer Information Saved Successfully ", null );
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                    errors.put( "Error storing the Material Transfer Lot information", null );
                }
            }
            else
            {
                 errors.put("Invalid Request" , null );
            }

            transferMaterialForm.setProcessType("0");
            transferMaterialForm.setProcessStepId(0);
            transferMaterialForm.setLocationId(0);
            transferMaterialForm.setLotId(0);
            transferMaterialForm.setWipLotsList( null );

            request.setAttribute( "processTypes", NewProductDAO.loadAllProcessesFromDB(null, false));
            request.setAttribute("action", action);
        }

        return mapping.findForward( "transferMaterial" );

    }
}